package com.huarui.purchaseOrder.service;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

import net.sf.json.JSONObject;

import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.exception.BizException;
import org.ewaf.framework.service.BaseService;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;

import com.huarui.code.dao.ICodeGenericDao;
import com.huarui.code.model.CodeGeneric;
import com.huarui.company.dao.ICompanyDao;
import com.huarui.company.model.Company;
import com.huarui.dictionary.DictionaryEnum;
import com.huarui.dictionary.service.DictionaryReadOnlyService;
import com.huarui.dictionary.service.DictionaryReadOnlyService.DictionaryResource;
import com.huarui.notice.INoticeService;
import com.huarui.notice.Notice;
import com.huarui.params.Params;
import com.huarui.params.ParamsHolder;
import com.huarui.part.dao.IPartPropertyDao;
import com.huarui.part.model.PartProperty;
import com.huarui.partner.dao.IPartnerDao;
import com.huarui.partner.model.Partner;
import com.huarui.purchaseOrder.dao.IPurchaseOrderDao;
import com.huarui.purchaseOrder.dao.IPurchaseOrderDetailDao;
import com.huarui.purchaseOrder.enums.ErrorCode;
import com.huarui.purchaseOrder.enums.PurchaseFunctionEnum;
import com.huarui.purchaseOrder.enums.PurchaseOperateMesEnum;
import com.huarui.purchaseOrder.model.PurOrSaleOrder;
import com.huarui.purchaseOrder.model.PurOrSaleOrderDetail;
import com.huarui.quotation.dao.IQuotationDao;
import com.huarui.receive.model.Receive;
import com.huarui.task.model.Task;
import com.huarui.task.taskEnum.BehaviourEnum;
import com.huarui.task.taskEnum.WorkFlowTaskNameEnum;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.FuncUtil;
import com.ibatis.sqlmap.client.SqlMapExecutor;

/**
 * 
 * @author ycf
 *
 */
public class PurchaseOrderService extends BaseService {
	
	public static final String PUR_ID_PARAM = "id";
	
	public static final String PUR_BUYER_ID_PARAM = "buyerId";
	
	public static final String PUR_ORDERS_ID_PARAM = "ordersId";
	
	public static final String PUR_VAR_GROUP_PARAM = "varGroup";
	
	public static final String PUR_CURRENTOR_ID_PARAM = "currentorId";
	
	private Logger logger = Logger.getLogger(PurchaseOrderService.class);
	private IPartPropertyDao partPropertyDao;
	private IPurchaseOrderDetailDao purchaseOrderDetailDao;
	private IQuotationDao quotationDao;
	private ICodeGenericDao codeGenericDao;
	private IPartnerDao partnerDao;
	private ICompanyDao companyDao;
	
	private INoticeService noticeService;
//	private DictionaryReadOnlyService dictionaryReadOnlyService;
	
	private PurOrSaleTaskService purOrSaleTaskService;
	

	public void setNoticeService(INoticeService noticeService) {
		this.noticeService = noticeService;
	}

	public void setCompanyDao(ICompanyDao companyDao) {
		this.companyDao = companyDao;
	}

	public void setPartnerDao(IPartnerDao partnerDao) {
		this.partnerDao = partnerDao;
	}

	public void setPurOrSaleTaskService(PurOrSaleTaskService purOrSaleTaskService) {
		this.purOrSaleTaskService = purOrSaleTaskService;
	}

	public void setCodeGenericDao(ICodeGenericDao codeGenericDao) {
		this.codeGenericDao = codeGenericDao;
	}

//	public void setDictionaryReadOnlyService(
//			DictionaryReadOnlyService dictionaryReadOnlyService) {
//		this.dictionaryReadOnlyService = dictionaryReadOnlyService;
//	}

	public void setQuotationDao(IQuotationDao quotationDao) {
		this.quotationDao = quotationDao;
	}

	private IPurchaseOrderDao getDao() {
		return (IPurchaseOrderDao) dao;
	}

	public void setPurchaseOrderDetailDao(
			IPurchaseOrderDetailDao purchaseOrderDetailDao) {
		this.purchaseOrderDetailDao = purchaseOrderDetailDao;
	}

	public void setPartPropertyDao(IPartPropertyDao partPropertyDao) {
		this.partPropertyDao = partPropertyDao;
	}
	
//    /**
//     * 查询本公司下已收货,但入库单状态为草稿、待仓库点数的订单id
//     * @param paramsMap
//     * @return 
//     */
//	@SuppressWarnings("unchecked")
//	public Map<String, Object> useOrderIds(Map<String, Object> paramsMap) {
//		SessionMessage sm = UserHolder.getCurrentSessionMessage();
//		Integer buyerId  = sm.getCompanyId();
//		
//		List<String> statusList = new ArrayList<String>();
//		statusList.add(Receive.STATUS_DRAFT);
//		statusList.add(Receive.STATUS_TO_INVENTORY);
//
//		paramsMap.put("buyerId", buyerId);
//		paramsMap.put("status", PurOrSaleOrder.STATUS_BUYER_ACPT);
//		paramsMap.put("statusList", statusList);
//		
//		List<Map> list = getDao().getOrdersByCondition(paramsMap);
//		Integer num = getDao().getOrdersCountByCondition(paramsMap);
//		
//		paramsMap.clear();
//		paramsMap.put("totalProperty", num);
//		paramsMap.put("root", list);
//		return paramsMap;
//	}

	/**
	 * 收货单引用订单
	 */
	public Map<String, Object> getAvailabeOrdersMess(Map<String, Object> paramsMap) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer buyerId = se.getCompanyId();
		
		paramsMap.put("buyerId", buyerId);
		paramsMap.put("status", PurOrSaleOrder.STATUS_AGREE_TO_RECIEVE);
		
		List<Map<String, Object>> list = getDao().getOrdersByCondition(paramsMap);
		Integer totalProperty = getDao().getOrdersCountByCondition(paramsMap);
		
		paramsMap.clear();
		paramsMap.put("totalProperty", totalProperty);
		paramsMap.put("root", list);
		
		return paramsMap;
	}

	public List<PartProperty> getPartPropertysByComplex(String[] params) {
		return partPropertyDao.getPartPropertyListByComplex(params);
	}

	public PurOrSaleOrderDetail getPurchaseOrderDetailsById(Integer id) {
		return purchaseOrderDetailDao.getPurchaseOrderDetailsById(id);
	}

	public void getQuotationsByComplex(Map<String, String> map) {
		this.quotationDao.getQuotationsByComplexCond(map);
	}

	/**
	 * 根据id查询采购订单，并且封装了级联明细信息集合
	 * 
	 * @param id
	 * @return
	 */
	public PurOrSaleOrder getPurchaseAndDetailsById(Integer id) {
		PurOrSaleOrder order = (PurOrSaleOrder) this.getDao().getById(id);
		List<PurOrSaleOrderDetail> details = this.purchaseOrderDetailDao
				.getPurchaseOrderDetailsByOrderId(id);
		order.setList(details);
		return order;
	}

	/**
	 * 查询出订单信息,判断出结果
	 * @param orderId
	 * @return
	 */
	public Map<String, Object> loadPurchaseByOrderId(Integer orderId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer buyerId = se.getCompanyId();
//		Integer userId = se.getUserId();

		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put(PUR_ID_PARAM, orderId);
		paramsMap.put(PUR_BUYER_ID_PARAM, buyerId);
		
		PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
		paramsMap.clear();
		
//		if( !isPurchaseCanBeModified(orders, userId)) {
//			putExceptionAlertMess(paramsMap, orders, userId);
//			return paramsMap;
//		}
//		
//		putCorrectAlertMess(paramsMap, orders);
		
		PurchaseOrderServiceUtil.toShowOrders(paramsMap, orders);
		
		return paramsMap;
	}
	
	
	/**
	 * 根据id和卖方id查询
	 * 
	 * @param id
	 * @param sellerId
	 * @return
	 */
	public PurOrSaleOrder getPurchaseByIdAndSellerId(int id, int sellerId) {
		PurOrSaleOrder order = (PurOrSaleOrder) getDao().getById(id);
		if (order != null && order.getSellerId() == sellerId) {
			return order;
		}
		return null;
	}

	/**
	 * 根据ordersId查找细表集合
	 * @param ordersId
	 * @return
	 */
	public List<PurOrSaleOrderDetail> getPurchaseOrderDetailsByOrderId(Integer ordersId) {
		
		List<PurOrSaleOrderDetail> list = this.purchaseOrderDetailDao
				.getPurchaseOrderDetailsByOrderId(ordersId);
		return list;
	}

	/**
	 * 新增采购订单时设置公用部分
	 * @param orders
	 * @param list
	 */
	private void setToInsertPurchase(PurOrSaleOrder orders, List<PurOrSaleOrderDetail> list) {
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		Integer buyerId = se.getCompanyId();
		String buyerName = se.getCompanyName();
		Integer userId = se.getUserId();
		String userName = se.getUserName();
		
		
		//判断在线 或非在线 订单，并设置流程ID
		/*if(orders.getSellerId() != null && orders.getSellerId() != 0) {
			orders.setWorkFlowId(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId());
		} else {
			orders.setWorkFlowId(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId());
		}*/
		
		//获得订单号
		String code = codeGenericDao.getNewCode(buyerId, CodeGeneric.PURCHASE_ORDER);
		orders.setCodeOfBuyer(code);
		orders.setCreatorCompanyId(buyerId);
		orders.setCreatorCompanyName(buyerName);
		orders.setCreatorId(userId);
		orders.setCreatorName(userName);
		orders.setBuyerId(buyerId);
		orders.setBuyerName(buyerName);
		
		if(orders.getSellerId() != null && orders.getSellerId() == 0) {
			orders.setSellerId(null);
		}
		
		if(orders.getSellerId() != null && orders.getSellerId() > 0) {
			Company seller = (Company) companyDao.getById(orders.getSellerId());
			if(seller != null) {
				orders.setSellerName(seller.getName());
			}
		}
		
		//设置金额
		BigDecimal amount = FuncUtil.addPurAmount(list);
		orders.setAmount(amount);
		
		Partner partner = (Partner) partnerDao.getById(orders.getPartnerIdByBuyer());
		if(partner != null) {
			orders.setPartnerNameByBuyer(partner.getName());
		}
	}
	
	/**
	 * 给明细表数据设置ordersId
	 * @param ordersId
	 * @param list
	 */
	private void setOrdersIdToDetails(Integer ordersId, List<PurOrSaleOrderDetail> list) {
		for(PurOrSaleOrderDetail detail : list) {
			detail.setOrdersId(ordersId);
		}
	}
	
	/**
	 * 采购订单插入双方客户资料
	 * @param partnerIdByBuyer
	 * @param orders
	 * @return
	 */
	private boolean insertPartnerToOrders(Integer partnerIdByBuyer, PurOrSaleOrder orders) {
		
		Partner buyerPartner = (Partner) partnerDao.getById(partnerIdByBuyer);
		if(buyerPartner == null) {
			logger.error("增加采购订单买方业务伙伴不存在");
			return false;
		}
		
		orders.setPartnerIdByBuyer(buyerPartner.getId());
		orders.setPartnerNameByBuyer(buyerPartner.getName());
		orders.setPartnerPyCodeByBuyer(buyerPartner.getPyCode());
		
		if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
			orders.setSellerId(null);
			orders.setSellerName(null);
			return true;
		}
		
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("ownerId", buyerPartner.getCompanyId());
		paramsMap.put("companyId", buyerPartner.getOwnerId());
		paramsMap.put("isDelete", Boolean.FALSE);
		paramsMap.put("relation", Partner.REALATION_CUSTOMER);
		
		Partner sellerPartner = partnerDao.findPartnerByOwnerId(paramsMap);
		if(sellerPartner == null) {
			logger.error("增加采购订单卖方业务伙伴不存在");
			return false;
		}
		
		orders.setPartnerIdBySeller(sellerPartner.getId());
		orders.setPartnerNameBySeller(sellerPartner.getName());
		orders.setPartnerPyCodeBySeller(sellerPartner.getPyCode());
//		orders.setSellerId(buyerPartner.getCompanyId());
//		orders.setSellerName(buyerPartner.getName());
		
		return true;
	}
	
	/**
	 * 保存采购订单
	 * @param orders
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> savePurAndDetails(final PurOrSaleOrder orders, final List<PurOrSaleOrderDetail> list) {
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					setToInsertPurchase(orders, list);
					
					orders.setCurrentorId(orders.getCreatorId());
					orders.setCurrentorName(orders.getCreatorName());
					
					orders.setCurrentCompanyId(orders.getBuyerId());
					orders.setCurrentCompanyName(orders.getBuyerName());
					
					if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
						orders.setActionId(BehaviourEnum.SAVE_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.SAVE_ONLINE_PURCHASEORDER.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.SAVE_NOT_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.SAVE_NOT_ONLINE_PURCHASEORDER.getActionName());
						
						for(PurOrSaleOrderDetail d : list) {
							d.setQuantity(d.getOrderQuantity());
						}
					}
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					
					if( !insertPartnerToOrders(orders.getPartnerIdByBuyer(), orders)) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					//保存
					dao.create(orders);
					
					setOrdersIdToDetails(orders.getId(), list);
					
					int num = purchaseOrderDetailDao.addBatch(list);
					if(num != list.size()) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					purOrSaleTaskService.saveOrders(orders);
					
					putCorrectAlertMess(paramsMap, orders);
					
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			logger.error("保存采购订单失败......", re);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_INITIAL);
		}
		return mesMap;
	}
	
	/**
	 * 提交采购订单
	 * @param orders
	 * @param list
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> submitPurAndDetails(final PurOrSaleOrder orders, final List<PurOrSaleOrderDetail> list) {
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					setToInsertPurchase(orders, list);
					
					orders.setSubmitterId(orders.getCreatorId());
					orders.setSubmitterName(orders.getCreatorName());
					orders.setCurrentorId(null);
					orders.setCurrentorName(null);
					
					if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
						orders.setCurrentCompanyId(orders.getSellerId());
						orders.setCurrentCompanyName(orders.getSellerName());
						orders.setActionId(BehaviourEnum.SUBMIT_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.SUBMIT_ONLINE_PURCHASEORDER.getActionName());
					} else {
						orders.setCurrentCompanyId(orders.getBuyerId());
						orders.setCurrentCompanyName(orders.getBuyerName());
						orders.setActionId(BehaviourEnum.SUBMIT_NOT_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.SUBMIT_NOT_ONLINE_PURCHASEORDER.getActionName());
						orders.setStatus(PurOrSaleOrder.STATUS_SELLER_DELIVERY);
						
						for(PurOrSaleOrderDetail d : list) {
							d.setQuantity(d.getOrderQuantity());
						}
					}
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					
					if( !insertPartnerToOrders(orders.getPartnerIdByBuyer(), orders)) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					//提交
					dao.create(orders);
					
					setOrdersIdToDetails(orders.getId(), list);
					
					int num = purchaseOrderDetailDao.addBatch(list);
					if(num != list.size()) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_INITIAL);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					purOrSaleTaskService.submitOrders(orders);
					
					sendNotice(orders);
					
					putCorrectAlertMess(paramsMap, orders);
					
					return paramsMap;
				}
			});
		}catch (RuntimeException re) {
			logger.error("提交采购订单失败......", re);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_INITIAL);
		}
		return mesMap;
	}
	
	
	private void sendNotice(PurOrSaleOrder orders) {
		if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
			Notice notice = new Notice();
			
			SessionMessage se = UserHolder.getCurrentSessionMessage();
			String compName = se.getCompanyName();
			Integer compId = se.getCompanyId();
			Integer recId = orders.getSellerId();
			
			notice.setTitle("收到一张在线订单");
			notice.setContent("<font color='red'>" + compName + "</font>" + "向贵公司下了一张在线订单<a href='javascript:openSaleOrderById(\"" + orders.getId() + "\");'>" + orders.getCodeOfBuyer() + "</a>");
			notice.setNoticeType(Notice.NOTICE_TYPE_USER);
			notice.setReceiveType(Notice.RECEIVE_TYPE_COMP);
			notice.setSenderId(compId);
			notice.setReceiverId(recId);
//			notice.setJsModuleId("task_list");
			
//			JSONObject jo = new JSONObject();
//			jo.put("id", orders.getId());
//			notice.setJsArgs(jo.toString());
			
			noticeService.send(notice, 67);
		}
	}
	
	/**
	 * 保存或提交采购订单
	 * @param orders
	 * @param list
	 * @return
	 */
	public Map<String, Object> insertPurAndDetails(PurOrSaleOrder orders, List<PurOrSaleOrderDetail> list) {
		if(PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
			return this.savePurAndDetails(orders, list);
		} else {
			return this.submitPurAndDetails(orders, list);
		}
	}

	/**
	 * 删除订单及明细
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> deletePurchaseAndDetails(final Integer ordersId) {
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap; 
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put(PUR_BUYER_ID_PARAM, buyerId);
					paramsMap.put(PUR_ID_PARAM, ordersId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if( !isPurchaseCanBeModified(orders, userId) ) {
						putExceptionAlertMess(paramsMap, orders, userId);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					boolean isOk = getDao().deleteById(ordersId);
					
					if( !isOk ) {
						putErrorAlertMess(paramsMap, orders.getStatus());
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
//					purchaseOrderDetailDao.delDetailsByOrderId(ordersId);
					
					putCorrectAlertMess(paramsMap, null);
					
					orders.setStatus(PurOrSaleOrder.STATUS_DELETED);
					
					if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.
							WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
						orders.setActionId(BehaviourEnum.DELETE_NOT_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.DELETE_NOT_ONLINE_PURCHASEORDER.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.DELETE_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.DELETE_ONLINE_PURCHASEORDER.getActionName());
					}
					purOrSaleTaskService.deleteOrders(orders);
					
					return paramsMap;
				}
			});
		} catch (Exception e) {
			logger.error("删除采购订单失败...", e);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_TMP);
		}
		return mesMap;
	}

	/**
	 * 更改当前处理人(收货引用)
	 * @param currentorId
	 * @param id
	 * @return
	 */
	public boolean updatePurCurrentorIdById( Integer id) {
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("currentorId", sm.getUserId());
		map.put("currentorName", sm.getUserName());
		map.put("id", id);
		map.put("buyerId", sm.getCompanyId());
		boolean success = getDao().updatePurCurrentorIdById(map);
		return success;
	}

	/**
	 * 更改当前处理人是否成功
	 * @param data.params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> updateCurrenterId(final Integer ordersId) {
		
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = sm.getCompanyId();
		final Integer userId = sm.getUserId();
		final String userName = sm.getUserName();
		
		Map<String, Object> mesMap = null;
		
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put(PUR_ID_PARAM, ordersId);
					paramsMap.put(PUR_BUYER_ID_PARAM, buyerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if( orders == null || !PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus()) ) {
						putExceptionAlertMess(paramsMap, orders, userId);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					paramsMap.put("id", ordersId);
					paramsMap.put("currentorId", userId);
					paramsMap.put("currentorName", userName);
					boolean isOK = getDao().updatePurCurrenterId(paramsMap);
					paramsMap.clear();
					
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, orders.getStatus());
						return paramsMap;
					}
					
					orders.setCurrentorId(userId);
					orders.setCurrentorName(userName);
					if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.
							WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
						orders.setActionId(BehaviourEnum.UPDATE_CURRENTOR_NOT_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.UPDATE_CURRENTOR_NOT_ONLINE_PURCHASEORDER.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.UPDATE_CURRENTOR_ONLINE_PURCHASEORDER.getActionId());
						orders.setActionName(BehaviourEnum.UPDATE_CURRENTOR_ONLINE_PURCHASEORDER.getActionName());
					}
					
					purOrSaleTaskService.dealWithOrders(orders);
					
					putCorrectAlertMess(paramsMap, orders);
					return paramsMap;
				}
			});
		} catch (Exception e) {
			logger.error("更改采购订单当前处理人失败...", e);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_TMP + "-");
		}
		return mesMap;
				
	}
	
	/**
	 * 根据ID获得订单主单
	 * @param orderId
	 * @return
	 */
	public Map<String, Object> getPurchaseById(Integer ordersId) {
		Map<String, Object> map = new HashMap<String, Object>();
		SessionMessage sem = UserHolder.getCurrentSessionMessage();
		Integer cmpId = sem.getCompanyId();
		map.put("buyerId", cmpId);
		map.put("id", ordersId);
		
		Map<String, Object> pur = getDao().getPurchaseById(map);
		
		String statusDes = DictionaryResource.getDictionaryValue(DictionaryEnum.GROUP_ORDER_STATUS, pur.get("status").toString());
		pur.put("statusDes", statusDes);
		
		return pur;
	}

	/**
	 * 订单高级查询数据分页集合
	 * @param paramsMap
	 * @return
	 */
//	public Map<String, Object> getPurChaseListByComplex(
//			Map<String, Object> paramsMap) {
//		SessionMessage sem = UserHolder.getCurrentSessionMessage();
//		Integer cmpId = sem.getCompanyId();
//		paramsMap.put("buyerId", cmpId);
//		paramsMap.put("pageSize", Params.PAGE_SIZE);
//		
//		Integer totalProperty = getDao().getPurchaseNumByComplex(paramsMap);
//		List<Map<String, Object>> list = getDao().getPurChaseListByComplex(paramsMap);
//		
//		paramsMap.clear();
//		paramsMap.put("totalProperty", totalProperty);
//		paramsMap.put("root", list);
//		
//		return paramsMap;
//	}

	/**
	 * 根据参数map 返回订单条目,关联字典表
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getOrderItems(Map<String, Object> map) {
		return purchaseOrderDetailDao.getOrderItems(map);
	}
	
	
	/**
	 * 根据订单号查询本公司明细信息集合
	 * @return
	 */
	public Map<String, Object> getPurDetailsInfoByComplex(Map<String, Object> paramsMap) {
		
		SessionMessage sem = UserHolder.getCurrentSessionMessage();
		Integer buyerId = sem.getCompanyId();
		paramsMap.put("buyerId", buyerId);
		
		Company buyer = (Company) companyDao.getById(buyerId);
		Integer totalProperty = 0;
		List<Map<String, Object>> list = null;
		if( buyer == null ) {
			list = new ArrayList<Map<String,Object>>();
			
			paramsMap.clear();
			paramsMap.put("totalProperty", totalProperty);
			paramsMap.put("root", list);
			
			return paramsMap;
		}
		
//		if(Company.PAID_NO == buyer.getPaid()) {
//			//流程ID不为在线采购订单
//			paramsMap.put("workFlowId", WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId());
//		}
		
		totalProperty = this.purchaseOrderDetailDao.getPurDetailsCountByComplex(paramsMap);
		list = this.purchaseOrderDetailDao.getPurDetailsInfoByComplex(paramsMap);

		paramsMap.clear();
		paramsMap.put("totalProperty", totalProperty);
		paramsMap.put("root", list);
		
		return paramsMap;
	}
	
	/**
	 * 根据订单号查询本公司主单信息集合
	 * @param code
	 * @return
	 */
	public Map<String, Object> getPurInfoByComplex(Map<String, Object> paramsMap) {
		
		SessionMessage sem = UserHolder.getCurrentSessionMessage();
		Integer buyerId = sem.getCompanyId();
		paramsMap.put("buyerId", buyerId);
		
		/*Company buyer = (Company) companyDao.getById(buyerId);
		Integer totalProperty = 0;
		List<Map<String, Object>> res_list = null;
		if( buyer == null ) {
			res_list = new ArrayList<Map<String,Object>>();
			
			paramsMap.clear();
			paramsMap.put("totalProperty", totalProperty);
			paramsMap.put("root", res_list);
			
			return paramsMap;
		}*/
		
//		if(Company.PAID_NO == buyer.getPaid()) {
//			//流程ID不为在线采购订单
//			paramsMap.put("workFlowId", WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId());
//		}
		
		Integer totalProperty = this.getDao().getPurchaseOrderListCountByComplex(paramsMap);
		List<Map<String, Object>> res_list = this.getDao().getPurchaseOrderListByComplex(paramsMap);
		
		for(Map<String, Object> map : res_list) {
			String statusDes = DictionaryResource.getDictionaryValue(
					DictionaryEnum.GROUP_ORDER_STATUS, map.get("status").toString());
			map.put("statusDes", statusDes);
		}
		
		paramsMap.clear();
		paramsMap.put("totalProperty", totalProperty);
		paramsMap.put("root", res_list);
		
		return paramsMap;
	}
	
	/**
	 * 计算出被删除的记录ID
	 * @param oldIds
	 * @param newIds
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<Integer> getDeleteIds(List<Integer> oldIds, List<Integer> newIds) {
		
		return ListUtils.subtract(oldIds, newIds);
		
//		List<Integer> deleteIds = new ArrayList<Integer>();
//		Map<Integer, String> map = new HashMap<Integer, String>();
//		for(Integer newId : newIds) {
//			map.put(newId, "");
//		}
//		for(Integer oldId : oldIds) {
//			if(!map.containsKey(oldId)) {
//				deleteIds.add(oldId);
//			}
//		}
//		return deleteIds;
	}
	
	private void setNewOrdersToOrders(PurOrSaleOrder pur, PurOrSaleOrder orders) {
		orders.setAreaId(pur.getAreaId());
		orders.setProvince(pur.getProvince());
		orders.setCity(pur.getCity());
		orders.setDistrict(pur.getDistrict());
		orders.setStreet(pur.getStreet());
		
		orders.setPhone(pur.getPhone());
		orders.setMobile(pur.getMobile());
		orders.setPostCode(pur.getPostCode());
		
		orders.setReceivedId(pur.getReceivedId());
		orders.setReceiverName(pur.getReceiverName());
		
		orders.setMemoOfBuyer(pur.getMemoOfBuyer());
		orders.setTransportType(pur.getTransportType());
		orders.setPaymentType(pur.getPaymentType());
		
		orders.setStatus(pur.getStatus());
	}
	
	/**
	 * 修改订单及明细
	 * @param order
	 * @param update
	 * @param add
	 * @param all
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> updatePurAndDetails(
			final PurOrSaleOrder pur, final List<PurOrSaleOrderDetail> update,
			final List<PurOrSaleOrderDetail> add, final List<Integer> all) {
		
		SessionMessage sm = UserHolder.getCurrentSessionMessage();
		
		final Integer userId = sm.getUserId();
		final String userName = sm.getUserName();
		final Integer buyerId = sm.getCompanyId();
//		final String buyerName = sm.getCompanyName();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put(PUR_ID_PARAM, pur.getId());
					paramsMap.put(PUR_BUYER_ID_PARAM, buyerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if( !isPurchaseCanBeModified(orders, userId)) {
						putExceptionAlertMess(paramsMap, orders, userId);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					setNewOrdersToOrders(pur, orders);
					
					List<Integer> ids = purchaseOrderDetailDao.getDetailsIdsByOrderId(orders.getId());
					List<Integer> deleteIds = getDeleteIds(ids, all);
					int del_num = purchaseOrderDetailDao.delBatch(deleteIds);
					if(del_num != deleteIds.size()) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					
					for(PurOrSaleOrderDetail d : update) {
						d.setOrdersId(orders.getId());
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
							d.setQuantity(d.getOrderQuantity());
						}
					}
					int update_num = purchaseOrderDetailDao.updateBatch(update);
					if(update_num != update.size()) {
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					
					for(PurOrSaleOrderDetail d : add) {
						d.setOrdersId(orders.getId());
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
							d.setQuantity(d.getOrderQuantity());
						}
					}
					int add_num = purchaseOrderDetailDao.addBatch(add);
					if(add_num != add.size()) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						return paramsMap;
					}
					
					
					BigDecimal amount = purchaseOrderDetailDao.getAmountByOrdersId(orders.getId());
					
					orders.setAmount(amount);
					
					if (PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus())) {
						orders.setSubmitterId(userId);
						orders.setSubmitterName(userName);
						orders.setCurrentorId(null);
						orders.setCurrentorName(null);
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.WORKFLOWID_TASKNAME_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
							orders.setCurrentCompanyId(orders.getSellerId());
							orders.setCurrentCompanyName(orders.getSellerName());
						} else {
							orders.setStatus(PurOrSaleOrder.STATUS_SELLER_DELIVERY);
						}
					} 
					
					boolean isOK = getDao().update(orders);
					
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						return paramsMap;
					}
					
					if(PurOrSaleOrder.STATUS_TMP.equals(orders.getStatus())) {
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.
								WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
							orders.setActionId(BehaviourEnum.UPDATE_NOT_ONLINE_PURCHASEORDER.getActionId());
							orders.setActionName(BehaviourEnum.UPDATE_NOT_ONLINE_PURCHASEORDER.getActionName());
						} else {
							orders.setActionId(BehaviourEnum.UPDATE_ONLINE_PURCHASEORDER.getActionId());
							orders.setActionName(BehaviourEnum.UPDATE_ONLINE_PURCHASEORDER.getActionName());
						}
						purOrSaleTaskService.updateOrders(orders);
					} else {
						if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.
								WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
							orders.setActionId(BehaviourEnum.UPDATE_AND_SUBMIT_NOT_ONLINE_PURCHASEORDER.getActionId());
							orders.setActionName(BehaviourEnum.UPDATE_AND_SUBMIT_NOT_ONLINE_PURCHASEORDER.getActionName());
						} else {
							orders.setActionId(BehaviourEnum.UPDATE_AND_SUBMIT_ONLINE_PURCHASEORDER.getActionId());
							orders.setActionName(BehaviourEnum.UPDATE_AND_SUBMIT_ONLINE_PURCHASEORDER.getActionName());
						}
						purOrSaleTaskService.updateToSubmitOrders(orders);
						
						sendNotice(orders);
					}
					
					
					putCorrectAlertMess(paramsMap, orders);
					return paramsMap;
				}
			});
		} catch(Throwable t) {
			logger.error("采购订单更新时发生数据库异常...", t);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_TMP);
		}
		return mesMap;
	}
	
	/**
	 * 是否可以被修改或删除
	 * @param order
	 * @param userId
	 * @return
	 */
	private boolean isPurchaseCanBeModified(PurOrSaleOrder order, Integer userId) {
		if(order != null && PurOrSaleOrder.STATUS_SELLER_DELIVERY.equals(order.getStatus())) {
			return Boolean.TRUE;
		}
		
		if(order != null && PurOrSaleOrder.STATUS_TMP.equals(order.getStatus()) 
				&& userId.equals(order.getCurrentorId())) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
	
	/**
	 * 封装发生数据库异常时返回到页面的信息
	 * @param mesMap
	 */
	private void putErrorAlertMess(Map<String, Object> mesMap, String status) {
		mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_ERROR.getKey());
		mesMap.put(Params.PUR_ORDER_STATUS_PARAM, status);
		mesMap.put("remove", "0");
		mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
	}
	
	
	/**
	 * 封装正确时返回到页面时的信息
	 * @param mesMap
	 * @param order
	 */
	private void putCorrectAlertMess(Map<String, Object> mesMap, PurOrSaleOrder order) {
		
		mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_OK.getKey());
		
		if(order != null) {
			mesMap.put(Params.PUR_ORDER_ID_PARAM, order.getId());
			mesMap.put(Params.PUR_ORDER_STATUS_PARAM, order.getStatus());
			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_PUR_FORM.getKey()
					+ ":"
					+ PurchaseFunctionEnum.lOAD_DETAILS_GRID.getKey()
					+ ":"
					+ PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey()
			);
		} else {
//			mesMap.put(Params.PUR_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_INITIAL);
//			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
			
//			mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_EXIST.getKey());
			
			mesMap.put("remove", "1");
			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
		}
		
	}
	
	/**
	 * 封装不符合条件时返回到页面时的信息
	 * @param mesMap
	 * @param order
	 * @param userId
	 */
	private void putExceptionAlertMess(Map<String, Object> mesMap, PurOrSaleOrder order, Integer userId) {
		if(order == null) {
//			mesMap.put(Params.PUR_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_INITIAL);
//			mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_EXIST.getKey());
//			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
			
			mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_EXIST.getKey());
			mesMap.put("remove", "1");
			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.CALLBACK_ALERT_FUNC.getKey());
			
		} else if( !order.getStatus().equals(PurOrSaleOrder.STATUS_TMP) && 
				!order.getStatus().equals(PurOrSaleOrder.STATUS_INITIAL)) {
			mesMap.put(Params.PUR_ORDER_ID_PARAM, order.getId());
			mesMap.put(Params.PUR_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT);
			mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_SUBMIT.getKey());
			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_PUR_FORM.getKey()
					                                + ":"
					                                + PurchaseFunctionEnum.lOAD_DETAILS_GRID.getKey()
					                                + ":"
					                                + PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey()
			);
		} else if( !userId.equals(order.getCurrentorId())) {
			mesMap.put(Params.PUR_ORDER_ID_PARAM, order.getId());
			mesMap.put(Params.PUR_ORDER_STATUS_PARAM, PurOrSaleOrder.STATUS_TMP + "-");
			mesMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_CURRENT_USER.getKey());
			mesMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_PUR_FORM.getKey()
			                    					+ ":"
			                    					+ PurchaseFunctionEnum.lOAD_DETAILS_GRID.getKey()
			                    					+ ":"
			                    					+ PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey()
			);
		} else {
			this.putCorrectAlertMess(mesMap, order);
		}
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, Object> takeOverSaleOrder(final Integer ordersId) {
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("id", ordersId);
					paramsMap.put("buyerId", buyerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder)getById(paramsMap);
					paramsMap.clear();
					
					if( !isPurchaseCanBeModified(orders, userId)) {
						transactionStatus.setRollbackOnly();
						putExceptionAlertMess(paramsMap, orders, userId);
						return paramsMap;
					}
					
					paramsMap.put("id", ordersId);
					String codeOfBuyer = codeGenericDao.getNewCode(buyerId, CodeGeneric.PURCHASE_ORDER);
					paramsMap.put("codeOfBuyer", codeOfBuyer);
					paramsMap.put("takeoverId", userId);
					
					boolean isOK = getDao().takeOverSaleOrder(paramsMap);
					paramsMap.clear();
					
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, orders.getStatus());
						return paramsMap;
					}
					
					orders.setTakeoverId(userId);
					purOrSaleTaskService.takeOverOrders(orders);
					
					putCorrectAlertMess(paramsMap, orders);
					
					return paramsMap;
					
				}
			});
		} catch (RuntimeException re) {
			logger.error("我来处理销售订单异常...", re);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_WAIT_BUYER_ACPT + "-");
		}
		return mesMap;
	}
	
	/**
	 * 处理销售订单
	 * @param pur
	 * @param update
	 * @param add
	 * @param all
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> takeOverUpdateOrSubmit(final PurOrSaleOrder pur, final List<PurOrSaleOrderDetail> update,
			final List<PurOrSaleOrderDetail> add, final List<Integer> all) {
		
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("id", pur.getId());
					paramsMap.put("buyerId", buyerId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder)getById(paramsMap);
					paramsMap.clear();
					
					if( !isPurchaseCanBeModified(orders, userId)) {
						transactionStatus.setRollbackOnly();
						putExceptionAlertMess(paramsMap, orders, userId);
						return paramsMap;
					}
					
					List<Integer> ids = purchaseOrderDetailDao.getDetailsIdsByOrderId(orders.getId());
					List<Integer> deleteIds = getDeleteIds(ids, all);
					int del_num = purchaseOrderDetailDao.delBatch(deleteIds);
					if(del_num != deleteIds.size()) {
//						paramsMap.clear();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					
					for(PurOrSaleOrderDetail d : update) {
						d.setOrdersId(orders.getId());
					}
					int update_num = purchaseOrderDetailDao.updateBatch(update);
					if(update_num != update.size()) {
//						paramsMap.clear();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						transactionStatus.setRollbackOnly();
						return paramsMap;
					}
					
					
					for(PurOrSaleOrderDetail d : add) {
						d.setOrdersId(orders.getId());
					}
					int add_num = purchaseOrderDetailDao.addBatch(add);
					if(add_num != add.size()) {
						transactionStatus.setRollbackOnly();
//						paramsMap.clear();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						return paramsMap;
					}
					
					
					BigDecimal amount = purchaseOrderDetailDao.getAmountByOrdersId(orders.getId());
					
					pur.setAmount(amount);
					
					boolean isOK = getDao().update(pur);
										
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, PurOrSaleOrder.STATUS_TMP);
						return paramsMap;
					}
					
					purOrSaleTaskService.takeOverUpdateOrders(pur);
					
					putCorrectAlertMess(paramsMap, pur);
					
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			mesMap = new HashMap<String, Object>();
			logger.error("处理对方销售订单修改时异常...", re);
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_WAIT_BUYER_ACPT);
		}
		
		return mesMap;
	}
	
	/**
	 * 退回销售订单
	 * @param ordersId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> turnBackSaleOrder(final Integer ordersId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("buyerId", buyerId);
					paramsMap.put("id", ordersId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder)getById(paramsMap);
					paramsMap.clear();
					
					if(orders == null || 
							PurOrSaleOrder.STATUS_WAIT_BUYER_ACPT.equals(orders.getStatus())) {
						transactionStatus.setRollbackOnly();
						putExceptionAlertMess(paramsMap, orders, userId);
						return paramsMap;
					}
					
					paramsMap.put("id", ordersId);
					paramsMap.put("status", PurOrSaleOrder.STATUS_INVALIDE);
					boolean isOK = getDao().turnBackSaleOrder(paramsMap);
					paramsMap.clear();
					
					if( !isOK ) {
						transactionStatus.setRollbackOnly();
						putErrorAlertMess(paramsMap, orders.getStatus());
						return paramsMap;
					}
					
					orders.setStatus(PurOrSaleOrder.STATUS_INVALIDE);
					purOrSaleTaskService.takeOverUpdateOrders(orders);
					
					putCorrectAlertMess(paramsMap, orders);
					return paramsMap;
				}
			});
		} catch(RuntimeException re) {
			logger.error("回退销售订单时异常...", re);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_WAIT_BUYER_ACPT);
		}
		
		return mesMap;
	}
	
	/**
	 * 同意收货
	 * @param ordersId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> agreeToRecieve(final Integer ordersId) {
		SessionMessage se = UserHolder.getCurrentSessionMessage();
		final Integer buyerId = se.getCompanyId();
		final Integer userId = se.getUserId();
		
		Map<String, Object> mesMap = null;
		try {
			mesMap = (Map<String, Object>) this.transactionTemplate.execute(new TransactionCallback() {
				@Override
				public Object doInTransaction(TransactionStatus transactionStatus) {
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					paramsMap.put("buyerId", buyerId);
					paramsMap.put("id", ordersId);
					
					PurOrSaleOrder orders = (PurOrSaleOrder) getById(paramsMap);
					paramsMap.clear();
					
					if(orders == null || 
							( !PurOrSaleOrder.STATUS_SELLER_DELIVERY.equals(orders.getStatus()) && 
							 !PurOrSaleOrder.STATUS_WAIT_SELLER_ACPT.equals(orders.getStatus()) ) ) {
						transactionStatus.setRollbackOnly();
						paramsMap.put(Params.PUR_ORDER_STATUS_PARAM, orders.getStatus());
						paramsMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_EXIST.getKey());
						paramsMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
						return paramsMap;
					}
					
					paramsMap.put("oldStatus", PurOrSaleOrder.STATUS_SELLER_DELIVERY);
					paramsMap.put("status", PurOrSaleOrder.STATUS_AGREE_TO_RECIEVE);
					paramsMap.put("id", orders.getId());
					
					boolean b = getDao().updateStatus(paramsMap);
					paramsMap.clear();
					
					if( !b) {
						transactionStatus.setRollbackOnly();
						paramsMap.put(Params.PUR_ORDER_STATUS_PARAM, orders.getStatus());
						paramsMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_NOT_EXIST.getKey());
						paramsMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
						return paramsMap;
					}
					
					
					orders.setStatus(PurOrSaleOrder.STATUS_AGREE_TO_RECIEVE);
					if(orders.getWorkFlowId().equals(WorkFlowTaskNameEnum.
							WORKFLOWID_TASKNAME_NOT_ONLINE_PURCHASE_ORDER.getWorkFlowId())) {
						orders.setActionId(BehaviourEnum.NOT_ONLINE_AGREE_TO_RECIEVE.getActionId());
						orders.setActionName(BehaviourEnum.NOT_ONLINE_AGREE_TO_RECIEVE.getActionName());
					} else {
						orders.setActionId(BehaviourEnum.ONLINE_AGREE_TO_RECIEVE.getActionId());
						orders.setActionName(BehaviourEnum.ONLINE_AGREE_TO_RECIEVE.getActionName());
					}
					purOrSaleTaskService.agreeToRecieve(orders);
					
					paramsMap.put(Params.PUR_ORDER_ID_PARAM, orders.getId());
					paramsMap.put(Params.PUR_ORDER_STATUS_PARAM, orders.getStatus());
					paramsMap.put(Params.PUR_ALERT_MES, PurchaseOperateMesEnum.ORDERS_OK.getKey());
					paramsMap.put(Params.PUR_LOADED_MESS_KEYS, PurchaseFunctionEnum.LOAD_PUR_FORM.getKey() + ":" + 
							PurchaseFunctionEnum.lOAD_DETAILS_GRID.getKey() + ":" + 
							PurchaseFunctionEnum.LOAD_BUTTONS_TOOL_BAR.getKey());
					return paramsMap;
					
				}
			});
		} catch (RuntimeException re) {
			logger.error("同意收货时异常...", re);
			mesMap = new HashMap<String, Object>();
			putErrorAlertMess(mesMap, PurOrSaleOrder.STATUS_SELLER_DELIVERY);
		}
		
		return mesMap;
	}

	public boolean recieve(Integer ordersId) {
		PurOrSaleOrder orders = (PurOrSaleOrder) getById(ordersId);
		return purOrSaleTaskService.recieve(orders );
	}
	
}
